package views;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import Helper.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.R;

import org.json.JSONArray;
import org.json.JSONObject;

import Const.PublicDefine;
import DataAccess.DeviceDataAccess;
import Interface.IAsynCallBackListener;


public class View_SelectGoods_DeviceInfo extends LinearLayout {
    public View view;
    private Context ctx;

    private TextView name;
    private TextView id;
    private TextView online;
    private LinearLayout goodsList;
    private DeviceDataAccess deviceDataAccess;
    private JSONObject deviceInfo;
    private String deviceId;
    private Thread getDeviceStateThread;
    private boolean exitflag = false;

    public View_SelectGoods_DeviceInfo(Context context, final String deviceId, String deviceOnline) throws Exception {
        super(context);
        ctx = context;
        view = inflate(context, R.layout.view_selectgoods_deviceinfo, this);
        this.deviceId = deviceId;

        name = view.findViewById(R.id.name);
        id = view.findViewById(R.id.id);
        online = view.findViewById(R.id.online);
        goodsList = view.findViewById(R.id.goodsList);

        //获取设备信息
        deviceDataAccess = new DeviceDataAccess(context);
        deviceInfo = deviceDataAccess.getById(deviceId);
        if (deviceInfo == null){
            deviceInfo = new JSONObject();
            deviceInfo.put("id",deviceId);
            deviceInfo.put("name","未命名");
            deviceDataAccess.setDevice(deviceInfo);
        }

        showGoodsList();

        //设置显示信息
        name.setText(deviceInfo.getString("name"));
        id.setText(deviceId);
        online.setText(deviceOnline);
    }


    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };

    public void alert(final String info) {
        Message msg = new Message();
        msg.obj = new IAsynCallBackListener() {
            @Override
            public void onFinish(Object sender, Object data) {
                View toastRoot = ((MainActivity)ctx).getLayoutInflater().inflate(R.layout.my_toast, null);
                Toast toast=new Toast(ctx);
                toast.setView(toastRoot);
                TextView tv=(TextView)toastRoot.findViewById(R.id.TextViewInfo);
                tv.setText(info);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }

            @Override
            public void onError(Object sender, Exception e) {

            }
        };
        mHandler.sendMessage(msg);
    }

    public void showGoodsList() throws Exception {
        deviceInfo = deviceDataAccess.getById(deviceId);
        JSONArray goodsArray = deviceInfo.getJSONArray("goodsList");
        goodsList.removeAllViews();
        for (int i = 0; i < goodsArray.length(); i++) {
            JSONObject goodsInfo = goodsArray.getJSONObject(i);
            View_SelectGoods_GoodsInfo goodsView = new View_SelectGoods_GoodsInfo(ctx, goodsInfo, new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    try {
                        JSONObject goodsInfo = (JSONObject) data;

                        goodsInfo.put("deviceId",deviceId);
                        new Dialog_TakeCup(ctx,goodsInfo,1);

                    } catch (Exception e) {
                        e.printStackTrace();
                        alert(e.getMessage());
                    }
                }

                @Override
                public void onError(Object sender, Exception e) {

                }
            });
            goodsList.addView(goodsView);
        }
    }


    //获取设备状态
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            int round = 30;
            while (!exitflag) {
                try {
                    round --;
                    if (round < 0){
                        int res = PublicDefine.colaReader.abortGivenSlaveDevice_GetWater(deviceId);
                        Log.write("colaReader","终止接杯res: "+res);
                        if (res == 0){
                            alert("已超时, 自动终止接杯");
                            return;
                        } else {
                            alert("超时自动终止接杯失败["+res+"]");
                        }
                    }
                    int stateRes = PublicDefine.colaReader.getGivenSlaveDeviceStatus(deviceId);
                    Log.write("colaReader","获取设备状态res: "+stateRes);
                    if (stateRes == 0){
                        int statusState = PublicDefine.colaReader.slave_DeviceInfo.getStatus_State();
                        Log.write("colaReader","接杯状态: "+statusState);
                        if (statusState == 0 || statusState == 4){
                            exitflag = true;
                            alert("接杯完成");
                            return;
                        } else {
                            Thread.sleep(1000);
                        }
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    alert(e.getMessage());
                }
            }
        }
    };

    @Override
    public void requestLayout() {
        super.requestLayout();
        post(measureAndLayout);
    }

    private final Runnable measureAndLayout = new Runnable() {
        @Override
        public void run() {
            measure(
                    MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
            layout(getLeft(), getTop(), getRight(), getBottom());
        }
    };
}
